<template>
	<div class="page">
		<h1>百度 > 短文本转语音</h1>
		<!-- 官方Demo: https://console.bce.baidu.com/tools/?_=1668482508529#/api?product=AI&project=%E8%AF%AD%E9%9F%B3%E6%8A%80%E6%9C%AF&parent=%E8%AF%AD%E9%9F%B3%E5%90%88%E6%88%90&api=text2audio&method=post -->

		<h3>1. 获取 token</h3>
		<p>请输入你应用的 client_id 和 client_secret 获取 access_token</p>
		<p style="font-weight: bold; color: orange">access_token: {{ auth }}</p>

		<el-input v-model.trim="clientId" placeholder="client_id ( 应用的API Key )" />
		<el-input v-model.trim="clientSecret" placeholder="client_secret ( 应用的 Secret Key )" />
		<el-button type="primary" @click="handleGetAccessToken">获取AccessToken</el-button>

		<h3>2. 文字转语音</h3>
		<p>免费的只能使用前4种语音</p>
		<el-radio-group v-model="currentPer">
			<el-radio-button label="1">度小宇</el-radio-button>
			<el-radio-button label="0">度小美</el-radio-button>
			<el-radio-button label="3">度逍遥（基础）</el-radio-button>
			<el-radio-button label="4">度丫丫</el-radio-button>
			<el-radio-button label="5003">度逍遥（精品）</el-radio-button>
			<el-radio-button label="5118">度小鹿</el-radio-button>
			<el-radio-button label="106">度博文</el-radio-button>
			<el-radio-button label="110">度小童</el-radio-button>
			<el-radio-button label="111">度小萌</el-radio-button>
			<el-radio-button label="103">度米朵</el-radio-button>
			<el-radio-button label="5">度小娇</el-radio-button>
		</el-radio-group>

		<br />
		<br />
		<el-input v-model.trim="inputText" placeholder="请输入你要转化的文本" />

		<el-button type="success" @click="handleTextToAudio">语音合成</el-button>

		<br />
		<br />
		<audio v-if="audioSrc" controls :src="audioSrc">您的浏览器不支持音频播放。</audio>
	</div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
export default {
	name: 'Baidu',
	data() {
		return {
			clientId: '5N39iuKBteVVb9eMVhFhdfhP',
			clientSecret: 'yBHJ45StgB6R5CWQt0j012IwGDfVjzoD',

			currentPer: '0',
			inputText: '你好，我是百度智能语音助手！',
			audioSrc: '',
		}
	},
	created() {},
	computed: {
		auth() {
			return localStorage.getItem('access_token')
		},
	},
	methods: {
		openMsg(message, type) {
			console.log('openMsg', ...arguments)
			this.$message({ showClose: true, message, type })
		},
		// 1. 获取AccessToken
		async handleGetAccessToken() {
			try {
				const option = {
					grant_type: 'client_credentials',
					client_id: this.clientId,
					client_secret: this.clientSecret,
				}

				const res = await axios.post('/baidu/oauth', qs.stringify(option))
				console.log('oauth res:', res, res.status, res.data)

				if (res.status !== 200 || res.data === '') {
					return this.openMsg('获取失败', 'warning')
				}

				this.openMsg('获取 token 成功', 'success')
				localStorage.setItem('access_token', res.data.access_token)

				this.clientId = ''
				this.clientSecret = ''
			} catch (error) {
				console.log('oauth err', error)
			}
		},
		// 2. 语音合成接口调用
		handleTextToAudio() {
			const token = localStorage.getItem('access_token')

			if (!token) {
				return this.openMsg('请先获取 token !', 'warning')
			}

			this.textToAudio(token)
		},

		async textToAudio(token) {
			const option = {
				tex: this.inputText, // 合成的文本
				tok: token,
				cuid: `${Math.floor(Math.random() * 1000000)}`, // 用户唯一标识，用来计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码，长度为60字符以内
				ctp: '1', // 客户端类型选择，web端填写固定值1
				lan: 'zh', // 固定值zh。语言选择,目前只有中英文混合模式，填写固定值zh
				per: this.currentPer, // 基础音库
			}

			const res = await axios.post('/baidu/text2audio', qs.stringify(option), {
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				responseType: 'blob',
			})

			if (res.status !== 200) {
				return this.openMsg(res.statusText, 'warning')
			}

			this.openMsg('语音合成成功', 'success')
			this.audioSrc = URL.createObjectURL(res.data)

			console.log('audioSrc:', this.audioSrc)
		},
	},
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.page {
	padding: 0 15px;

	.el-input {
		width: 300px;
		margin-right: 10px;
	}
}
</style>
